package wei.qiang.ye.springcomponentdemo.my;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import wei.qiang.ye.springcomponentdemo.domain.Strawberry;

/**
 * 使用ImportBeanDefinitionRegistrar来手动往IOC容器导入组件
 */
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        final String beanName = "strawberry";
        //判断IOC容器中是否包含了名称为strawberry的组件
        boolean contain = registry.containsBeanDefinition(beanName);
        if (!contain) {
            //如果没有，则手动通过BeanDefinitionRegistry的registerBeanDefinition方法注册一个
            RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(Strawberry.class);
            registry.registerBeanDefinition(beanName, rootBeanDefinition);
        }
    }
}
